﻿using Microsoft.Extensions.Hosting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace EfCore.Web.Services
{
    public class TimerHostedService
        : IHostedService
    {
        private bool _stopped = true;
        private Task _backgroundTask;
        public Task StartAsync(CancellationToken cancellationToken)
        {
            _backgroundTask = BackgroundTask(cancellationToken);
            _stopped = false;
            return Task.CompletedTask;
        }

        private Task BackgroundTask(CancellationToken cancellationToken)
        {
            var timer = new Timer(state => Callback(state), DateTime.Now.Second, 1000, 1000);
            return Task.CompletedTask;
        }

        private void Callback(object state)
        {
            while (!_stopped)
            {
                Console.WriteLine(state);
            }
        }

        public Task StopAsync(CancellationToken cancellationToken)
        {
            _stopped = true;
            return Task.CompletedTask;
        }
    }
}
